import { atom } from "jotai";
import type { User } from "@/lib/types";
import { atomWithStorage } from "jotai/utils";
import { getToken, getUserInfo } from "@/lib/api/user";

export const tokenAtom = atomWithStorage("token", "", undefined, {
  getOnInit: true,
});
export const userAtom = atom<{
  user: User | null;
  roles: string[];
  permissions: string[];
}>({
  user: null,
  roles: [],
  permissions: [],
});
export const isAuthPendingAtom = atom(true);

export const isLoginAtom = atom((get) => !!get(userAtom).user);

export const isAdminAtom = atom((get) =>
  get(userAtom).roles.includes("common_admin"),
);

export const authAtom = atom(null, async (get, set, signal?: AbortSignal) => {
  const token = get(tokenAtom);
  console.log({ token });
  if (!token) {
    set(isAuthPendingAtom, false);
    return;
  }
  const userRes = await getUserInfo(token, signal);
  if (userRes.code !== 200) {
    set(isAuthPendingAtom, false);
    throw userRes;
  }
  set(userAtom, {
    user: userRes.user,
    roles: userRes.roles,
    permissions: userRes.permissions,
  });
  set(isAuthPendingAtom, false);
  return userRes.user;
});

export const loginAtom = atom(
  null,
  async (get, set, data: { username: string; password: string }) => {
    const tokenRes = await getToken(data);
    if (tokenRes.code !== 200) {
      throw tokenRes;
    }
    set(tokenAtom, tokenRes.token);
    const userRes = await getUserInfo(tokenRes.token);
    if (userRes.code !== 200) {
      throw userRes;
    }
    set(userAtom, {
      user: userRes.user,
      roles: userRes.roles,
      permissions: userRes.permissions,
    });
    return userRes.user;
  },
);

export const logoutAtom = atom(null, (get, set) => {
  set(tokenAtom, "");
  set(userAtom, { user: null, roles: [], permissions: [] });
});
